#include "Character.h"

Character::Character(btDiscreteDynamicsWorld* pWorld,
                     btCylinderShape* pCollisionShape,
                     Ogre::SceneManager* pSceneManager,
                     OpenSteer::Vec3 position,
                     const char* mesh):
  _pWorld(pWorld),
  _pCollisionShape(pCollisionShape),
  _pSceneManager(pSceneManager)
{

  // Ogre --------------------------------------------------------------

  // Entidad
  _pEntity = _pSceneManager->createEntity(mesh);

  // Nodos
  _pNode = _pSceneManager->getRootSceneNode()->createChildSceneNode();

  Ogre::Vector3 ogrePosition(position.x, position.y, position.z);
  _pNode->setPosition(ogrePosition);
  _pSubNode = _pNode->createChildSceneNode();
  _pSubNode->attachObject(_pEntity);

  // Bullet ------------------------------------------------------------

  // MotionState
  btVector3 bulletPosition = openSteerToBullet(position);

  // Situar la base del personaje sobre el plano XZ
  bulletPosition.setY(_pCollisionShape->getHalfExtentsWithoutMargin().y());

  _pMotionState =
    new MyMotionState(btTransform(btQuaternion(0, 0, 0, 1),
                                  bulletPosition), _pNode);

  // ConstructionInfo
  btScalar mass = 1;
  btVector3 fallInertia(0,0,0);
  _pCollisionShape->calculateLocalInertia(mass, fallInertia);

  btRigidBody:: btRigidBodyConstructionInfo
    bodyCI(mass,_pMotionState, _pCollisionShape,
                 fallInertia);

  // Cuerpo rígido
  _pRigidBody = new btRigidBody(bodyCI);
  _pRigidBody->setLinearFactor(btVector3(1,0,1));
  _pRigidBody->setAngularFactor(btVector3(0,0,0));

  _pWorld->addRigidBody(_pRigidBody);

  // OpenSteer ---------------------------------------------------------

  // Bullet vehicle
  setRigidBody(_pRigidBody);
  setRadius(_pCollisionShape->getRadius());
  setMaxForce(0);
  setMaxSpeed(0);
}

Character::~Character() {

  _pWorld->removeRigidBody(_pRigidBody);
  delete _pMotionState;
  delete _pRigidBody;

  //_pSceneManager->destroySceneNode(_pNode);
  _pSceneManager->destroyEntity(_pEntity);
}

int Character::getLife() {
  return _life; }

void Character::setLife(int life) {
  _life = life; }

void Character::yaw(const Ogre::Radian& angle) {
  _pNode->yaw(angle); }

Ogre::Vector3 Character::getPosition() {
  return _pNode->getPosition(); }

Ogre::SceneNode*
Character::getSceneNode() { return _pNode; }

bool Character::doDamage(int damage)
{
  bool r = false;

  std::cout << "Ouch! Life = " << _life - 1 << std::endl;

  if ((_life -= damage) <= 0)
  {
    doDead();
    r = true;
  }

  return r;
}

void
Character::doDead() {

  std::cout << "I'm dead" << std::endl;
}
